#include <iostream>
#include <string.h>
#include <iomanip>
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
//#include <stdlib.h>
using namespace std;

extern char *optarg;
extern int optind;

int l_flag = 0;
int a_flag = 0;
int R_flag = 0;
char filename[256][256];
int len = 0;

int list_files(const char *dirname)
{
	struct dirent *entry;
	struct stat stt;
	DIR * dp = opendir(dirname);
	while(entry = readdir(dp))
	{
		if (a_flag == 0 && strncmp(entry->d_name,".",1) == 0)
			continue;
		if(stat(entry->d_name,&stt) >= 0 && S_ISDIR(stt.st_mode))
		{
			strcpy(filename[len++],entry->d_name);
			strcat(filename[len-1],"/");
			if (R_flag == 1)
			{
				list_files(filename[len-1]);
			}
		}
		else
			strcpy(filename[len++],entry->d_name);
	}
	closedir(dp);
	return 0;
}

int print_files()
{	
	int i,j;
	int rank[256];
	int k = 0;
	for (i = 0 ; i < len ; i ++)
	{
		rank[i] = 0;
	}
	for (i = 0 ; i < len ; i ++)
	{
		for (j = 0 ; j < len ; j ++)
		{
			int temp;
			temp = strcmp(filename[i],filename[j]);
			if (temp > 0)
			{
				rank[i] += 1;
			}
			else if (temp < 0)
			{
				rank[i] = rank[i];
			}
			else if (temp == 0)
			{
				;
			}
		}
	}
	for (i = 0 ; i < len ; i ++)
	{
		for (j = 0 ; j < len ; j ++)
		{
			if (rank[j] == i)
			{
				cout << setiosflags(ios::left) << setw(5) << filename[j] << "\t";
				k ++;
			}
			if (k == 6)
			{
				cout << endl;
				k = 0;
			}
		}
	}
	cout << endl;
	return 0;
}

int main(int argc, char *argv[])
{
	int i;
	char ch;

	while ((ch = getopt(argc, argv, "alR")) != -1)
	{
		switch(ch)
		{
			case 'a':
				a_flag = 1;
				break;
			case 'l':
				l_flag = 1;
				break;
			case 'R':
				R_flag = 1;
				break;
			default:
				cout << "This parameter is illegal." << endl;
				return 1;
		}
	}
	if (optind < argc)
	{
		for (i = optind; i < argc ; i ++)
		{
			len = 0;
			cout << argv[i] << ":" << endl;
			list_files(argv[i]);
			print_files();
		}
	}
	else
	{	
		list_files(".");
		print_files();
	}

	return 0;
}
